package com.gxuwz.leave.servlet;

import com.gxuwz.leave.context.AppContext;
import com.gxuwz.leave.entity.Instructor;
import com.gxuwz.leave.entity.User;
import com.gxuwz.leave.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet(name = "userServlet", urlPatterns = {"/user"})
public class UserServlet extends BaseHttpServlet{
    private final static String VIEW_EDIT = "/WEB-INF/views/user/user_edit.jsp";
    private final static String ACTION_EDIT = "/user?action=get";
    private final static String ACTION_LOGIN = "/index";

    //问题记录，这里用@Autowired不行
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        userService = AppContext.getBean(UserService.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        String view = ErrorPage_500;
        try{
            switch (action){
                case "get":
                    String userid = (String) req.getSession().getAttribute("userID");
                    System.out.println("当前用户的ID为："+userid);
                    User user = userService.findUser(userid);
                    view = VIEW_EDIT;
                    req.setAttribute("user",user);
                    break;
                case "edit":
                    user = new User();
                    user.setUserid(req.getParameter("userid"));
                    user.setFullname(req.getParameter("fullname"));
                    user.setPassword(req.getParameter("password"));
                    user.setTelephone(req.getParameter("telephone"));
                    userService.editUser(user);
                    //清除session，退出登录
                    req.getSession().invalidate();
                    //重定向退出登录，直接退出选择
                    resp.sendRedirect(req.getContextPath() + ACTION_LOGIN);
                    return;
                default:
            }
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("message", e.getMessage());
            req.setAttribute("operation", "failure");
            view = ACTION_EDIT;
        }
        super.doDispatch(req,resp,view);
    }
}
